#include "fast_build_helper.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <iostream>
#include <fstream>

#define COMPILE_COMMAND "make CC='fcc gcc' "

using std::ifstream;
using std::ios;

namespace build_helper {

  /**
  * To get the dependency data from the Makefile, we need to retrieve the
  * information and transform it into a certain format
  *
  * @Param makefile_name
  * @Param output_file_name the formatted dependency information file
  */
  void PreProcessMakefileDeps(const char* makefile_name,
      char* output_file_name) {
  }

  int ExecuteCommand(const char* command, const char* path) {
    chdir(path);
    system(command);
    return 0;
  }

  int ExecuteCommand(const char* command) {
    system(command);
    return 0;
  }

  /**
  * Get the build command to be used with make
  *
  * @Param argc 
  * @Param argv[] the arguments passed to fmake
  *
  * @Returns char* command which the user has to delete 
  */
  char* GetBuildCommand(int argc, const char* argv[]) {
    char* args = new char[5000];

    // Construct the make command with the parameters and execute it
    strcpy(args, COMPILE_COMMAND);
    for (int i = 1; i < argc; i++) {
      strcat(args, argv[i]);
      strcat(args, " ");
    }
    return args;
  }

  /**
  * Starts the build process using command make
  *
  * @Param argc
  * @Param argv[] the arguments passed into the client
  */
  void StartBuild(int argc, const char* argv[], const char* path) {

    // Construct the make command with the parameters and execute it
    char* args = GetBuildCommand(argc, argv);
    ExecuteCommand(args, path);
    delete[] args;
  }

  /**
  * Returns the filesize of a given file
  *
  * @Param file_name
  *
  * @Returns  filesize if file exist, else returns -1 
  */
  long GetFileSize(const char* file_name) {
    long begin, end;
    ifstream file(file_name);
    if (file.is_open()) {
      begin = file.tellg();
      file.seekg(0, ios::end);
      end = file.tellg();
      file.close();
      return (end - begin);
    }
    return -1;
  }
}
